package ip

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"time"
)

type ipInfoJsonResult struct {
	Code int    `json:"code"`
	Data IpInfo `json:"data"`
}
type IpInfo struct {
	Country   string `json:"country"`
	Area      string `json:"area"`
	Region    string `json:"region"`
	City      string `json:"city"`
	County    string `json:"county"`
	Isp       string `json:"isp"`
	CountryId string `json:"country_id"`
	AreaId    string `json:"area_id"`
	RegionId  string `json:"region_id"`
	CityId    string `json:"city_id"`
	CountyId  string `json:"county_id"`
	IspId     string `json:"isp_id"`
}

func GetIpInfo(ipAddr string) (rt *IpInfo, err error) {
	client := http.Client{Timeout: 2 * time.Second}
	var resp *http.Response
	resp, err = client.Get(`http://ip.taobao.com/service/getIpInfo.php?ip=` + ipAddr)
	if err != nil {
		return
	}
	defer func() {
		if resp != nil {
			_ = resp.Body.Close()
		}
	}()
	var buffer [512]byte
	var n int
	result := bytes.NewBuffer(nil)
	for {
		n, err = resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			return
		}
	}
	info := &ipInfoJsonResult{}
	err = json.Unmarshal(result.Bytes(), info)
	if err == nil {
		if info.Code == 0 {
			rt = &info.Data
		}
	}
	return
}
